<template>
  <div v-loading="pageLoading" class="app-container">
    <!-- 返回按钮始终在顶部 -->
    <div class="top-actions">
      <el-button @click="handleBack">
        <template #icon>
          <ArrowLeft />
        </template>
        返回
      </el-button>
      <el-button @click="handleClear">
        <template #icon>
          <Refresh />
        </template>
        清空表单
      </el-button>
    </div>

    <el-card shadow="never">
      <el-form
        ref="dataFormRef"
        class="form-container"
        :model="formData"
        :rules="rules"
        label-width="90px"
        :disabled="isReadOnly"
      >
        <template v-if="isEdit">
          <el-divider content-position="left">订单信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="订单号">
                <span>{{ formData.id || "-" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-tag :type="configStore.getOrderStatusType(formData.status)" size="large">
                  {{ configStore.getOrderStatusLabel(formData.status) }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col v-if="isEdit" :span="6">
              <el-form-item label="创建人">
                <UserLabel :model-value="formData.createdId" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="处理人">
                <UserLabel :model-value="formData.handleId" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="formData.type" @change="handleTypeChange">
                <el-radio
                  v-for="orderType in configStore.getOrderTypes"
                  :key="orderType.value"
                  :value="orderType.value"
                >
                  {{ orderType.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 根据类型动态渲染不同组件 -->
        <MechanicalPrint
          v-if="formData.type === 0"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />
        <DigitalPrint
          v-else-if="formData.type === 1"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />
        <DigitalPrintCustom
          v-else-if="formData.type === 2"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />
        <SingleLayerBag
          v-else-if="formData.type === 3"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />
        <MechanicalPrint2
          v-else-if="formData.type === 4"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />
        <OtherType
          v-else-if="formData.type === 5"
          :form-data="formData"
          :is-add-mode="isAddMode"
          :is-quote-mode="isQuoteMode"
          @update:form-data="handleFormDataUpdate"
        />

        <!-- 价格变更历史 -->
        <el-divider v-if="!isAddMode && priceHistory.length > 0" content-position="left">
          价格变更历史
        </el-divider>
        <el-row v-if="!isAddMode && priceHistory.length > 0" :gutter="20">
          <el-col :span="24">
            <el-form-item label-width="0px">
              <PriceHistoryDisplay :history-data="priceHistory" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">备注信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label-width="0px" prop="remark1">
              <el-input
                v-model="formData.remark1"
                maxlength="2000"
                show-word-limit
                rows="5"
                type="textarea"
                placeholder="备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="text-center mt-4">
              <!-- 新增模式显示保存按钮 -->
              <el-button v-if="isAddMode" type="primary" :loading="loading" @click="handleSubmit">
                保存
              </el-button>
              <!-- 业务员模式在status=0时可以设置为处理中 -->
              <el-button
                v-if="isQuoteMode && formData.status === 0"
                v-hasPerm="['vt:vt-order-form:handle']"
                type="primary"
                :loading="loading"
                @click="handleSetProcessing"
              >
                设置为处理中...
              </el-button>
              <!-- 报价员模式在status=0,1时可以修改总价，调用handle接口 -->
              <el-button
                v-if="
                  isQuoteMode &&
                  (formData.status === 0 || formData.status === 1 || formData.status === 3)
                "
                v-hasPerm="['vt:vt-order-form:handle']"
                type="primary"
                :loading="loading"
                @click="handleQuote"
              >
                修改报价
              </el-button>
              <!-- 业务员模式在status=2时可以确定订单 -->
              <el-button
                v-else-if="isSalesMode && formData.status === 1"
                v-hasPerm="['vt:vt-order-form:edit']"
                type="primary"
                :loading="loading"
                @click="handleConfirmOrder"
              >
                确定订单
              </el-button>
              <!-- 其他编辑模式显示更新按钮 -->
              <el-button
                v-else-if="!isReadOnly && isEdit"
                type="primary"
                :loading="loading"
                @click="handleSubmit"
              >
                更新
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { ArrowLeft, Refresh } from "@element-plus/icons-vue";
import { useConfigStore } from "@/store/modules/config.store.js";
import { useVtOrderStoreHook } from "@/store/modules/vt-order.store.js";
import VtOrderAPI from "@/api/vt/vt-order.js";
import VtOrderPriceHistoryAPI from "@/api/vt/vt-order-price-history.js";
import MechanicalPrint from "./components/MechanicalPrint.vue";
import DigitalPrint from "./components/DigitalPrint.vue";
import DigitalPrintCustom from "./components/DigitalPrintCustom.vue";
import SingleLayerBag from "./components/SingleLayerBag.vue";
import MechanicalPrint2 from "./components/MechanicalPrint2.vue";
import OtherType from "./components/OtherType.vue";

defineOptions({
  name: "VtOrderForm",
  inheritAttrs: false,
});

const configStore = useConfigStore();

/**
 * 根据数量获取价格比例配置
 */
async function getPriceRatioByQuantity(quantity) {
  // 确保价格损耗数据已加载
  if (!configStore.priceLossData) {
    await configStore.loadPriceLossData();
  }
  return configStore.getPriceRatioByQuantity(quantity);
}

const priceRatio = ref(15); // 默认值

// 初始化价格比例
const initPriceRatio = async () => {
  priceRatio.value = await getPriceRatioByQuantity(10000);
};

const route = useRoute();
const router = useRouter();

const dataFormRef = ref();
const loading = ref(false);
const pageLoading = ref(false);

// 是否为编辑模式
const isEdit = computed(() => !!route.query.id);

// 模式类型：1=业务员模式，2=报价员模式
const mode = computed(() => parseInt(route.query.t) || 0);

// 是否为业务员模式
const isSalesMode = computed(() => mode.value === 1);

// 是否为报价员模式
const isQuoteMode = computed(() => mode.value === 2);

// 是否为新增模式
const isAddMode = computed(() => !route.query.id);

// 是否只读模式（状态为2时只能查看）
const isReadOnly = computed(() => formData.status === 2);

// 默认表单数据
const getDefaultFormData = (isCustom = false) => {
  const currentPriceRatio = priceRatio.value || 15;

  return {
    type: 0,
    bagType: "",
    bagProcess: "",
    material: isCustom ? "" : [],
    compositeType: isCustom ? "" : [],
    surfaceFee: isCustom ? "" : [], // 印刷颜色
    accessory: isCustom ? "" : [], // 工艺名称
    rollMaterial: "",
    rollCompositeType: [],
    selectedSize: "",
    l: null,
    w: null,
    h: null,
    thickness: null,
    quantity1: null,
    quantity2: null,
    quantity3: null,
    weight1: null,
    weight2: null,
    weight3: null,
    price1: null,
    price2: null,
    price3: null,
    finalPrice1: null,
    finalPrice2: null,
    finalPrice3: null,
    plateFee: null,
    remark1: "",
    remark2: "",
    status: 0,
    createdId: null,
    handleId: null,
    attach: null,
    typeNum: null,
    id: null,
    priceRatio1: currentPriceRatio,
    priceRatio2: currentPriceRatio,
    priceRatio3: currentPriceRatio,
    // 单层袋印相关字段
    color: "",
    customColor: "",
    adhesiveWidth: null,
    cardWidth: null,
    isPrint: false,
    printSide: "",
    printColorCount: null,
    // 机印2相关字段
    valveType: "",
    zipperType: "",
    spoutType: "",
    spoutBagType: "",
  };
};

// 价格变更历史
const priceHistory = ref([]);

// 报价单表单数据
const formData = reactive(getDefaultFormData());

// 报价单表单校验规则
const rules = reactive({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  bagType: [{ required: true, message: "请选择袋型", trigger: "change" }],
  l: [{ required: true, message: "请输入长度", trigger: "blur" }],
  w: [{ required: true, message: "请输入宽度", trigger: "blur" }],
  thickness: [{ required: true, message: "请输入单面厚度", trigger: "blur" }],
});

/** 数组转逗号分隔字符串 */
function arrayToString(arr) {
  return Array.isArray(arr) ? arr.join(",") : arr;
}

/** 逗号分隔字符串转数组 */
function stringToArray(str) {
  return str ? str.split(",").filter((item) => item.trim()) : [];
}

/** 准备提交数据：转换数组字段并删除不需要的字段 */
function prepareSubmitData(formData) {
  const submitData = { ...formData };

  if (formData.type === 3) {
    // 胶条宽度和卡头宽度使用remark3存储，逗号分隔
    const hValues = [];
    if (formData.adhesiveWidth) {
      hValues.push(formData.adhesiveWidth);
    }
    if (formData.cardWidth) {
      hValues.push(formData.cardWidth);
    }
    submitData.remark3 = hValues.join(",");

    // 处理surfaceFee字段
    submitData.surfaceFee = arrayToString(formData.surfaceFee);
  } else if (formData.type === 4) {
    // 机印2类型：处理配件相关字段
    const accessoryFields = [];
    if (formData.valveType) {
      accessoryFields.push(formData.valveType);
    }
    if (formData.zipperType) {
      accessoryFields.push(formData.zipperType);
    }
    if (formData.spoutType) {
      accessoryFields.push(formData.spoutType);
    }
    if (formData.spoutBagType) {
      accessoryFields.push(formData.spoutBagType);
    }
    submitData.accessory = accessoryFields.join(",");
  } else if (formData.type === 5) {
    // 其他类型：将前端特有字段存储到remark3
    const frontendOnlyFields = {
      subType: formData.subType,
      boxType: formData.boxType,
      shape: formData.shape,
      weight: formData.weight,
      coating: formData.coating,
      printing: formData.printing,
      process: formData.process,
      deliveryForm: formData.deliveryForm,
      handleStyle: formData.handleStyle,
      openingStyle: formData.openingStyle,
    };

    // 过滤掉空值
    const filteredFields = {};
    Object.keys(frontendOnlyFields).forEach((key) => {
      if (
        frontendOnlyFields[key] !== null &&
        frontendOnlyFields[key] !== undefined &&
        frontendOnlyFields[key] !== ""
      ) {
        filteredFields[key] = frontendOnlyFields[key];
      }
    });

    // 存储为JSON字符串
    submitData.remark3 = JSON.stringify(filteredFields);

    // 处理后端支持的字段
    submitData.material = arrayToString(formData.material);
    submitData.compositeType = arrayToString(formData.compositeType);
    submitData.surfaceFee = arrayToString(formData.surfaceFee);
    submitData.accessory = arrayToString(formData.accessory);
  } else if (formData.type !== 2) {
    // 处理卷膜字段映射
    if (formData.bagType === "卷膜") {
      // 卷膜模式：使用 rollMaterial 和 rollCompositeType 映射到 material 和 compositeType
      submitData.material = formData.rollMaterial || "";
      submitData.compositeType = arrayToString(formData.rollCompositeType);
    } else {
      // 非卷膜模式：使用原来的 material 和 compositeType
      submitData.material = arrayToString(formData.material);
      submitData.compositeType = arrayToString(formData.compositeType);
    }
    // 处理其他数组字段
    submitData.surfaceFee = arrayToString(formData.surfaceFee);
    submitData.accessory = arrayToString(formData.accessory);
  }

  const fieldsToDelete = [
    "selectedSize",
    "rollMaterial",
    "rollCompositeType",
    "cal_price1",
    "cal_price2",
    "cal_price3",
    "priceRatio1",
    "priceRatio2",
    "priceRatio3",
    "valveType",
    "zipperType",
    "spoutType",
    "spoutBagType",
    "adhesiveWidth",
    "cardWidth",
    "color",
    "customColor",
    "isPrint",
    "printSide",
    "printColorCount",
    "subType",
    "boxType",
    "shape",
    "weight",
    "coating",
    "printing",
    "process",
    "deliveryForm",
    "handleStyle",
    "openingStyle",
  ];

  fieldsToDelete.forEach((field) => {
    delete submitData[field];
  });

  return submitData;
}

/** 处理子组件表单数据更新 */
function handleFormDataUpdate(updatedData) {
  Object.assign(formData, updatedData);
}

/** 返回列表页 */
function handleBack() {
  router.replace({
    path: "/vt/vt-order",
  });
}

/** 清空表单 */
function handleClear() {
  resetFormData();
  router.replace({
    path: "/vt/vt-form",
  });
}

/** 提交报价单表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;

      const submitData = prepareSubmitData(formData);

      const id = route.query.id;
      if (id) {
        VtOrderAPI.update(id, submitData)
          .then(() => {
            // 更新本地订单状态，避免自己修改的数据发送通知
            if (submitData.status !== undefined) {
              const vtOrderStore = useVtOrderStoreHook();
              vtOrderStore.updateLocalOrderStatus(parseInt(id), submitData.status);
            }

            ElMessage.success("修改成功");
            handleBack();
          })
          .finally(() => (loading.value = false));
      } else {
        VtOrderAPI.add(submitData)
          .then(() => {
            ElMessage.success("新增成功");
            handleBack();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 处理报价 (报价员使用) */
function handleQuote() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;

      const submitData = prepareSubmitData(formData);

      const id = route.query.id;
      VtOrderAPI.handle(id, submitData)
        .then(() => {
          // 更新本地订单状态，避免自己修改的数据发送通知
          // 报价处理后状态变为已报价(1)
          const vtOrderStore = useVtOrderStoreHook();
          vtOrderStore.updateLocalOrderStatus(parseInt(id), 1);

          ElMessage.success("报价处理成功");
          handleBack();
        })
        .finally(() => (loading.value = false));
    }
  });
}
/** 设置为处理中 */
function handleSetProcessing() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;

      const submitData = prepareSubmitData(formData);
      submitData.status = 3;
      formData.status = 3;

      const id = route.query.id;
      VtOrderAPI.update(id, submitData)
        .then(() => {
          // 更新本地订单状态，避免自己修改的数据发送通知
          const vtOrderStore = useVtOrderStoreHook();
          vtOrderStore.updateLocalOrderStatus(parseInt(id), 3);

          ElMessage.success("已设置为处理中，请及时处理");
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 确定订单 (业务员使用) */
function handleConfirmOrder() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;

      const submitData = prepareSubmitData(formData);
      submitData.status = 2;

      const id = route.query.id;
      VtOrderAPI.update(id, submitData)
        .then(() => {
          // 更新本地订单状态，避免自己修改的数据发送通知
          const vtOrderStore = useVtOrderStoreHook();
          vtOrderStore.updateLocalOrderStatus(parseInt(id), 2);

          ElMessage.success("订单确定成功");
          handleBack();
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 获取价格变更历史 */
function loadPriceHistory(orderId) {
  if (!orderId) return;

  const requestOrderId = orderId;

  VtOrderPriceHistoryAPI.getPage({ orderId })
    .then((data) => {
      if (route.query.id !== requestOrderId) {
        console.log("订单ID已改变，忽略此次价格历史数据");
        return;
      }

      priceHistory.value = data.list || [];
    })
    .catch((error) => {
      console.error("获取价格历史失败:", error);
      priceHistory.value = [];
    });
}

/** 初始化数据 */
function initData() {
  if (isEdit.value) {
    const id = route.query.id;
    const currentMode = route.query.t;

    const requestParams = { id, mode: currentMode };

    VtOrderAPI.getFormData(id)
      .then((data) => {
        if (route.query.id !== requestParams.id || route.query.t !== requestParams.mode) {
          console.log("路由参数已改变，忽略此次接口返回数据");
          return;
        }

        const processedData = {
          ...data,
        };

        if (data.type === 3) {
          // 解析remark3字段（胶条宽度和卡头宽度）
          if (data.remark3) {
            const hValues = data.remark3.split(",").filter((item) => item.trim());
            processedData.adhesiveWidth = hValues[0] ? parseFloat(hValues[0]) : null;
            processedData.cardWidth = hValues[1] ? parseFloat(hValues[1]) : null;
          }

          // 解析surfaceFee字段到印刷相关字段
          const surfaceFeeArray = stringToArray(data.surfaceFee);
          processedData.surfaceFee = surfaceFeeArray;

          // 根据surfaceFee内容解析印刷信息
          processedData.isPrint = surfaceFeeArray.includes("印刷");
          processedData.printSide =
            surfaceFeeArray.find((item) => item === "单面" || item === "双面") || "";

          // 解析印刷颜色数
          const colorMatch = surfaceFeeArray.find((item) => item.includes("色"));
          if (colorMatch) {
            const colorCount = parseInt(colorMatch.replace("色", ""));
            processedData.printColorCount = isNaN(colorCount) ? null : colorCount;
          } else {
            processedData.printColorCount = null;
          }
        } else if (data.type === 4) {
          // 机印2类型：解析配件字段
          const accessoryArray = stringToArray(data.accessory);

          // 解析配件信息
          processedData.valveType =
            accessoryArray.find(
              (item) =>
                item.includes("气阀类型") ||
                ["气阀类型1", "气阀类型2", "气阀类型3", "无气阀"].includes(item)
            ) || "";

          // 从配件数组中获取拉链类型
          processedData.zipperType =
            accessoryArray.find((item) => ["易撕拉链", "普通拉链", "无拉链"].includes(item)) ||
            "无拉链";

          processedData.spoutType =
            accessoryArray.find((item) => ["正吸嘴", "斜吸嘴"].includes(item)) || "";

          processedData.spoutBagType =
            accessoryArray.find((item) => ["自立", "三边封", "四边封"].includes(item)) || "";

          // 清空原accessory字段避免混淆
          processedData.accessory = [];
        } else if (data.type === 5) {
          // 其他类型：解析remark3字段中的JSON数据
          if (data.remark3) {
            try {
              const frontendFields = JSON.parse(data.remark3);
              Object.assign(processedData, frontendFields);
            } catch (error) {
              console.error("解析remark3 JSON数据失败:", error);
            }
          }

          // 处理后端支持的字段
          processedData.compositeType = stringToArray(data.compositeType);
          processedData.surfaceFee = stringToArray(data.surfaceFee);
          processedData.accessory = stringToArray(data.accessory);
        } else if (data.type !== 2) {
          processedData.material = stringToArray(data.material);
          processedData.compositeType = stringToArray(data.compositeType);
          processedData.surfaceFee = stringToArray(data.surfaceFee);
          processedData.accessory = stringToArray(data.accessory);
          // 处理卷膜字段映射回显
          if (data.bagType === "卷膜") {
            // 卷膜模式：将 material 和 compositeType 映射到 rollMaterial 和 rollCompositeType
            processedData.rollMaterial = data.material || "";
            processedData.rollCompositeType = stringToArray(data.compositeType);
            // 清空原字段，避免混淆
            processedData.material = [];
            processedData.compositeType = [];
          } else {
            // 非卷膜模式：确保卷膜字段为空
            processedData.rollMaterial = "";
            processedData.rollCompositeType = [];
          }
        }

        Object.assign(formData, processedData);

        loadPriceHistory(id);
      })
      .catch((error) => {
        console.error("获取表单数据失败:", error);
      });
  } else {
    resetFormData();
    priceHistory.value = [];
  }
}

/** 重置表单数据为默认值 */
function resetFormData() {
  Object.assign(formData, getDefaultFormData(formData.type === 2 || formData.type === 3));
}

// 监听路由变化，重新初始化数据
watch(
  () => [route.query.id, route.query.t],
  ([newId, newT], [oldId, oldT]) => {
    if (newId !== oldId || newT !== oldT) {
      resetFormData();
      priceHistory.value = [];
      initData();
    }
  },
  { immediate: false }
);

/** 处理类型切换 */
const handleTypeChange = () => {
  console.log(`类型切换: ${formData.type}，清空表单`);
  const currentType = formData.type; // 保存新的类型值
  resetFormData(); // 重置表单
  formData.type = currentType; // 恢复新的类型值
};

onMounted(async () => {
  // 加载配置数据
  if (!configStore.loaded) {
    // 只有在没有缓存数据时才显示加载状态
    if (!configStore.hasCacheData()) {
      pageLoading.value = true;
    }
    await configStore.loadConfigs();
    pageLoading.value = false;
  }

  // 加载价格损耗数据
  await configStore.loadPriceLossData();

  // 初始化价格比例
  await initPriceRatio();

  initData();
});
</script>

<style scoped>
.top-actions {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.text-center {
  text-align: center;
}
.mt-4 {
  margin-top: 1rem;
}
.form-container {
  :deep(.el-form-item__label) {
    color: black;
    font-weight: bold;
  }
}
</style>
